package com.hwadee.property.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hwadee.property.mapper.ParkingMapper;
import com.hwadee.property.pojo.Parking;
import com.hwadee.property.service.IParkingService;
import com.hwadee.property.dto.PageResult;
import com.hwadee.property.util.ErrorCodes;
import com.hwadee.property.util.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.Date;
import java.util.List;

@Service
public class ParkingServiceImpl extends ServiceImpl<ParkingMapper, Parking> implements IParkingService {

    @Autowired
    private ParkingMapper parkingMapper;

    @Override
    public PageResult<Parking> getPage(int current, int size, Long communityId, String location, String status, Date createTime, Date updateTime) {
        // 校验参数是否合法
        if (current < 1 || size < 1) {
            throw new BusinessException(ErrorCodes.INVALID_PARAMETER, "分页参数无效！");
        }

        // 确保 current 至少为 1，size 至少为 1
        int offset = (current - 1) * size;

        try {
            // 计算总记录数
            int total = parkingMapper.countParking(communityId, location, status, createTime, updateTime);

            // 只有当 total > 0 时才查询数据
            List<Parking> records = (total > 0) ? parkingMapper.getParkingList(communityId, location, status, createTime, updateTime, size, offset) : Collections.emptyList();

            // 返回分页结果
            return new PageResult<>(total, current, size, records);
        } catch (Exception e) {
            // 捕获数据库操作异常
            throw new BusinessException(ErrorCodes.DATABASE_ERROR, "查询车位数据失败：" + e.getMessage());
        }
    }

    @Override
    public Parking getFreeParking(Long communityID) {
        try {
            return this.list(new LambdaQueryWrapper<Parking>().eq(Parking::getStatus, "空闲").eq(Parking::getCommunityId, communityID)).get(0);
        } catch (Exception e) {
            // 捕获数据库操作异常
            throw new BusinessException(ErrorCodes.NOT_FOUND, "获取空闲车位失败：" + e.getMessage());
        }
    }

    @Override
    public List<Parking> listByCommunityId(Long communityId) {
        try {
            return this.list(new LambdaQueryWrapper<Parking>().eq(Parking::getCommunityId, communityId));
        } catch (Exception e) {
            // 捕获数据库操作异常
            throw new BusinessException(ErrorCodes.NOT_FOUND, "获取小区车位列表失败：" + e.getMessage());
        }
    }
}
